
var ARCHIVES_TABLE_CREATE = "CREATE TABLE IF NOT EXISTS ARCHIVES(id INTEGER PRIMARY KEY AUTOINCREMENT,kind,firstname,lastname,amount,unit,startDate,endDate,archiveDate,comment)";
/**
 * The database
 */
var dbShell;
/**
 * Boolean for the state of the database tables (created or not) 
 */
var dbCreated=false;
/**
 * The HTML Generator
 */
var generator = new Generator();

/**
 * deviceready envent listener
 */
document.addEventListener("deviceready", function (){
	onDeviceReady();
}, false);
/**
 * onDeviceReady function
 */
function onDeviceReady(){
	
	dbShell = window.openDatabase("mainDB", "1","MoneyIODB",10000 );
	if(!dbCreated){//if database is not initialized
		dbShell.transaction(createTables,errorCB,successCB);
	}
    dbShell.transaction(queryDBArchivesEntries,errorCB);
}

function createTables(tx){
	
	tx.executeSql(ARCHIVES_TABLE_CREATE);    
}

function queryDBArchivesEntries(tx){
	tx.executeSql("SELECT * FROM ARCHIVES",[],querySuccessArchivesEntries,errorCB);
}

function querySuccessArchivesEntries(tx, results){
	insertEntriesInDOM (results);
}

function errorCB(err)
{
	alert("SQL error:"+ err.message);
}
/**
 * When the tables are created
 * @returns {Boolean}
 */
function successCB()
{
	dbCreated = true;
	return true;
}


function insertEntriesInDOM (results){
	var list = "";
	var len = results.rows.length;
	for(var i = 0;i<len;i++){
		list += generator.generateHtmlForOneEntry(
				new MoneyIOEntry
				(results.rows.item(i).id, results.rows.item(i).kind, results.rows.item(i).firstname,
						results.rows.item(i).lastname, results.rows.item(i).startDate, 
						results.rows.item(i).endDate, results.rows.item(i).amount, 
						results.rows.item(i).unit, results.rows.item(i).comment));
	}
	$("ul#archives").append(list);
}